package mybatis.sqlsession.defaults;

import mybatis.cfg.Configuration;
import mybatis.proxy.MapperProxy;
import mybatis.sqlsession.SqlSession;
import utils.DateSourceUtil;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * sqlSession实现类
 */
public class DefaultSqlSession implements SqlSession {
  private Configuration cfg;
  private Connection conn;

  public DefaultSqlSession(Configuration cfg) {
    this.cfg = cfg;
    this.conn = DateSourceUtil.getConnection(cfg);
  }

  /**
   * 创建代理对象方法
   * @param classInterface
   * @param <E>
   * @return
   */
  public <E> E getMapper(Class<E> classInterface) {
    E obj = (E)Proxy.newProxyInstance(
            classInterface.getClassLoader(),
            new Class[]{classInterface},
            new MapperProxy(cfg.getMappers(), conn)
    );
    return obj;
  }

  /**
   * 释放资源
   */
  public void close() {
    if (conn != null) {
      try {
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
}
